package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.KHDBConfig
import cn.com.kh.hst.ThreeDesUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONObject
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat
import java.time.Instant
import cn.com.kh.getProperty;

/**
 *
 * @Title: autoHSTApplyMoreUsersTask
 * @Description:华盛证券 服务顾问申请更多客户请求 定时读取申请临时表 下发。
 * @author: chieh
 * @date 2023-01-12 12:32:00
 *
 */

public class autoHSTApplyMoreUsersTask implements CallBackInvoke{
    private static final Logger log = LoggerFactory.getLogger(autoHSTApplyMoreUsersTask.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        String inData = "";
        String outData = "";
        String rec_id = "";
        String staff_id = "";
        String rolegroup_id = "";
        int limit_num = 0;
        String dataSourceID = "dataSource";

        //查询有没有处理中的批次  0是处理中 1是已完成
        try {
            def batchnumList = eliteBean.chaxun_sql("select rec_id,staff_id,rolegroup_id,limit_num from hst_apply_moreusers_task where state=0 order by rec_id asc ", "dataSource");
            log.debug("申请批次数量:" + batchnumList.size());

            if (batchnumList.size() > 0) {
                //循环捞取的 申请任务批次
                for (int i = 0; i < batchnumList.size(); i++) {
                    Map batchnumMap = batchnumList.get(i);
                    rec_id = batchnumMap.get("rec_id");//批次任务
                    staff_id = batchnumMap.get("staff_id");
                    rolegroup_id = batchnumMap.get("rolegroup_id");
                    limit_num = batchnumMap.get("limit_num");//当前申请配置的限额
                    log.debug("rec_id:" + rec_id+"	staff_id:" + staff_id+"	limit_num:" + limit_num);

                    int staffIssueNO=0;

                    //获取限额后 根据限额循环 拿
                    for (int j = 0; j < limit_num; j++) {
                        int reFlag  = assignTasks(eliteBean, staff_id);
                        if (reFlag==1) {
                            staffIssueNO=staffIssueNO+1;
                        }else if(reFlag==0){
                            log.debug("规则筛选出的任务量不足!");
                        }else if(reFlag==-1){
                            log.debug("接口异常！跳出分配！");
                            break;//跳出当前循环
                        }
                    }
                    //更新分配情况 标识为已处理 assign_num
                    eliteBean.update("Update hst_apply_moreusers_task Set  state=1,assign_num='" + staffIssueNO + "',modifytime=now() where rec_id='" + rec_id + "' ", "dataSource");
                }
            }else{
                //无申请任务
                log.debug("系统检查，无申请任务！");
            }
            outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";
        } catch (Exception e) {
            log.error("接口处理异常",e);
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";

        }

    }

    //分配任务，1：成功返回、0：失败返回、-1：接口返回失败；
    public static int assignTasks(EliteBean eliteBean,  String staffid) {

        int reFlag = 0;
        def groupid = "";
        def counselor_id = "";//服务顾问id

        List groupidlist = eliteBean.chaxun_sql("SELECT DEFAULTROLEGROUP, counselor_id FROM staff WHERE staff_id = '" + staffid + "' ", "dataSource");
        if (groupidlist.size() > 0) {
            groupid = groupidlist.get(0).get("DEFAULTROLEGROUP");
            counselor_id = groupidlist.get(0).get("counselor_id");
            log.debug("groupid:" + groupid+"	counselor_id:" + counselor_id);

        }

        List objectivelist = eliteBean.chaxun_sql("SELECT DISTINCT o.objective_guid, o.customer_guid, o.handleby_id, o.handlegroup_id, c.customer_id ,IFNULL(distributionnumber,0)+1 as distributionnumber FROM objective o LEFT JOIN assign_his a ON o.objective_guid = a.objective_guid LEFT JOIN customer c ON c.customer_guid = o.customer_guid  WHERE 1=1 AND o.recycledate IS NOT NULL AND o.retaindeadline < now() AND a.OLDHANDLEBY_ID <> '" + staffid + "'  LIMIT 1", "dataSource");
        log.debug("objectivelist:" + objectivelist + "; objectivelist.size():" + objectivelist.size());

        if (objectivelist.size() > 0) {
            def objective_guid = objectivelist.get(0).get("objective_guid");
            def handleby_id = objectivelist.get(0).get("handleby_id");
            def distributionnumber = objectivelist.get(0).get("distributionnumber");
            log.debug("objective_guid:" + objective_guid+"	handleby_id:" + handleby_id+"	distributionnumber:" + distributionnumber);

            //拼接报文，调用'华盛服顾绑定'接口
            try {
                //华盛接口连续调用可能异常 添加1S睡眠
                Thread.sleep(1 * 1000);

                String injson = ""
                //分配
                if(handleby_id==''||handleby_id==null){
                    injson = "{\"hsNo\":\"" + objectivelist.get(0).get("customer_id") + "\", \"managerId\":\"" + counselor_id + "\", \"divideType\":0, \"divideNumber\":" + distributionnumber + "}"
                }else{//调整
                    injson = "{\"hsNo\":\"" + objectivelist.get(0).get("customer_id") + "\", \"managerId\":\"" + counselor_id + "\", \"divideType\":1}"
                }
                String sysurl = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain");//配置本地接口地址
                String doURL = sysurl + "/aipHSTBindCounselor";
                log.debug("injson:" + injson + "; doURL" + doURL);
                Map<String, String> headMap = new HashMap<String, String>();
                headMap.put("Content-Type", "application/x-www-form-urlencoded");
                def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
                log.debug("绑定接口返回:" + getResult);
                JSONObject jsonObject = new JSONObject(getResult);
                String code = GetJV(jsonObject, "result");
                log.debug("绑定接口返回code：" + code);
                //api接口 成功 则分配
                if (code == "1") {
                    reFlag = 1;
                    String[] data = new String[3];
                    data[0] = "UPDATE objective SET HANDLEBY_ID='" + staffid + "', HANDLEGROUP_ID='" + groupid + "', recycledate = NULL, retaindeadline = NULL, distributiontime = now(), distributionnumber = distributionnumber+1,objectivesubstatus='' WHERE 1=1 AND objective_guid = '" + objective_guid + "'";
                    data[1] = "UPDATE elitetask SET HANDLEBY_ID='" + staffid + "', HANDLEGROUP_ID='" + groupid + "', createddate = NOW(),objectivesubstatus='',MODIFIEDDATE=null where 1=1 AND objective_guid = '" + objective_guid + "'";
                    data[2] = "INSERT INTO Assign_His (Assign_Guid, Customer_Guid, Objective_Guid, Oldhandlegroup_Id, Oldhandleby_Id, Newhandlegroup_Id, Newhandleby_Id, Assigngroup_Id, Assignby_Id, Assigndate, recovery_guid,Success_Guid) VALUES (Uuid(), '" + objectivelist.get(0).get("customer_guid") + "', '" + objective_guid + "', '" + objectivelist.get(0).get("handlegroup_id") + "', '" + objectivelist.get(0).get("handleby_id") + "', '" + groupid + "', '" + staffid + "', 'SYSTEM', 'SELITE', Now(), '' ,'申请更多客户')";
                    int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                    log.debug("dataresult:" + dataresult);
                } else {
                    reFlag = -1;
                }

            } catch (Exception e) {
                log.error(e.getMessage(), e);
                reFlag = -1;
            }
        } else {
            reFlag = 0;
        }
        return reFlag;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;

    }
}

